package com.xmg.server.goods.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.xmg.server.goods.mapper.BrandMapper;
import com.xmg.shop.api.domain.Brand;
import com.xmg.shop.api.page.PageResult;
import com.xmg.shop.api.query.BrandQueryObject;
import com.xmg.shop.api.service.IBrandService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;

@Service
public class BrandServiceImpl implements IBrandService {
    @Autowired
    private BrandMapper brandMapper;

    public int delete(Long id) {
        return brandMapper.deleteByPrimaryKey(id);
    }

    public int save(Brand record) {
        Date date = new Date();
        record.setCreatedDate(date);
        record.setFoundDate(date);
        record.setLastModifiedDate(date);
        return brandMapper.insert(record);
    }

    public Brand get(Long id) {
        return brandMapper.selectByPrimaryKey(id);
    }

    public List<Brand> selectAll() {
        return brandMapper.selectAll();
    }

    public int update(Brand record) {
        Brand brand = this.get(record.getId());
        brand.setLogo(record.getLogo());
        brand.setLastModifiedDate(new Date());
        brand.setUrl(record.getUrl());
        brand.setArea(record.getArea());
        brand.setChineseName(record.getChineseName());
        brand.setEnglishName(record.getEnglishName());
        brand.setSequence(record.getSequence());
        brand.setArea(record.getArea());
        brand.setDescription(record.getDescription());
        return brandMapper.updateByPrimaryKey(brand);
    }

    @Override
    public PageResult query(BrandQueryObject qo) {
        Long count = brandMapper.queryPageCount(qo);
        if (count <= 0) {
            return PageResult.empty(qo.getPageSize());
        }
        List data = brandMapper.queryPageData(qo);
        return new PageResult(data, count.intValue(), qo.getCurrentPage(), qo.getPageSize());
    }


    public void saveORupdate(Brand brand, Long[] catalogId) {
        if(brand.getId()==null){
            if(catalogId==null){
                throw new RuntimeException("请选择商品的分类");
            }
            this.save(brand);
            //保存中间表
            for (int i = 0; i < catalogId.length; i++) {
                brandMapper.insetRelation(brand.getId(),catalogId[i]);
            }
        }else{
            this.update(brand);
            //更新中间表
            if(catalogId!=null){
                brandMapper.deleteRelationByBrandId(brand.getId());
                for (int i = 0; i < catalogId.length; i++) {
                    brandMapper.insetRelation(brand.getId(),catalogId[i]);
                }
            }
        }
    }

    @Override
    public List<Brand> selectBrandNameAndId() {
        return brandMapper.selectBrandNameAndId();
    }

}
